package com.study.zouchao.superproject.comtaskdetail;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.study.zouchao.superproject.R;
import com.study.zouchao.superproject.base_zou.MyBaseFragment;
import com.study.zouchao.superproject.base_zou.ZouImgLoader;
import com.study.zouchao.superproject.comtaskdetail.model.TaskDetailResult;
import com.study.zouchao.superproject.login.model.entity.User;
import com.study.zouchao.superproject.logininterceptor.LoginInterceptor;
import com.study.zouchao.superproject.logininterceptor.LoginInterceptor_C;
import com.study.zouchao.superproject.logininterceptor.LoginStatusUtil;
import com.study.zouchao.superproject.travellist.TravelPresenter;
import com.study.zouchao.superproject.util.App;
import com.study.zouchao.superproject.util.StringUtils;
import com.study.zouchao.superproject.util.ToastUtils;
import com.study.zouchao.superproject.util.ui.CircleImageView;

import java.nio.channels.ReadableByteChannel;
import java.util.IllegalFormatCodePointException;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2017/6/20.
 */

public class TaskDetailFragment extends MyBaseFragment implements ITaskDetailContract.ITaskDetailView, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.id_rv_support_lists)
    RecyclerView mRvSupport;

    @BindView(R.id.id_task_detail_refresh)
    SwipeRefreshLayout mRefreshing;

    @BindView(R.id.id_task_detail_headimg)
    CircleImageView mIvHeadimg;

    @BindView(R.id.id_tv_nickname)
    TextView mTvNickname;

    @BindView(R.id.id_tv_createTime)
    TextView mTvCreateTime;

    @BindView(R.id.id_tv_content)
    TextView mTvContent;

    @BindView(R.id.id_tv_timearea)
    TextView mTvTimeArea;

    @BindView(R.id.id_tv_sex)
    TextView mTvSex;

    @BindView(R.id.id_tv_welfare)
    TextView mTvWelfare;

    @BindView(R.id.id_tv_welfare_price)
    TextView mTvWelfarePrice;

    @BindView(R.id.id_tv_contact)
    TextView mTvContact;

    @BindView(R.id.id_tv_self_desc)
    TextView mTvSelfDesc;

    @BindView(R.id.id_support_num)
    TextView mTvSupportNum;

    @BindView(R.id.id_tv_act)
    TextView mTvAct;

    @BindView(R.id.id_tv_gotologin)
    TextView mTvGotoLogin;

    private String mUserName = null;
    private int mUserId = -1;

    private ITaskDetailContract.ITaskDetailPresenter mPresenter;
    public static String KEY_TASK_ID = "KEY_TASK_ID";

    private int mTaskId;

    private int mTaskStatus;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
    }

    private void init() {
        initInfos();
        mRefreshing.setOnRefreshListener(this);
        mPresenter = new TaskDetailPresenter(getActivity(), this, mTaskId);
        mPresenter.initRecyclerView(mRvSupport);
        mTvGotoLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginInterceptor.attemptIntent(getActivity(), LoginInterceptor_C.ACTIVITY_TASK_DETAIL_ACTIVITY, null);
            }
        });
    }

    private void initInfos() {
        Intent intent = getActivity().getIntent();
        mTaskId = intent.getIntExtra(KEY_TASK_ID, -1);
        if (mTaskId == -1) {
            ToastUtils.showShort(getActivity(), "缺少taskId");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        updateLoginUi();
    }

    private void updateLoginUi() {
        boolean isLogin = LoginStatusUtil.getLoginStatus(getActivity());
        if (isLogin) showLoginUi();
        else showNotLoginUi();
    }

    private void showLoginUi() {
        mTvGotoLogin.setVisibility(View.GONE);
        mTvAct.setVisibility(View.VISIBLE);
        User userBean = LoginStatusUtil.getLoginDataByBean(getActivity());
        if (userBean != null) {
            mUserId = userBean.getUserId();
        }
    }

    private void showNotLoginUi() {
        mUserName = null;
        mTvGotoLogin.setVisibility(View.VISIBLE);
        mTvAct.setVisibility(View.GONE);
    }

    @Override
    public void onRefresh() {
        mPresenter.onRefreshingData();
    }


    @Override
    protected View getLoadingTargetView() {
        return getCurrentFragmentRootView().findViewById(R.id.id_loading_task_detail);
    }

    @Override
    protected int getFragmentLayoutID() {
        return R.layout.fragment_task_detail;
    }


    /**
     * 显示数据(取到数据后)
     *
     * @param data
     */
    @Override
    public void loadInfos(TaskDetailResult.TaskDetailDataBean data) {
        TaskDetailResult.TaskDetailDataBean.TaskDetailBean detailBean = data.getTaskDetail();
        if (detailBean == null) {
            ToastUtils.showShort(getActivity(), "未获取数据");
            return;
        }
        mTaskStatus = data.getTaskStatus();
        //
        if (mTvNickname != null)
            mTvNickname.setText(StringUtils.isEmpty(detailBean.getSponsorNickname()) ? "" : detailBean.getSponsorNickname());
//        Log.d("头像", detailBean.getSponsorHeadimg());
        if (mIvHeadimg != null)
            ZouImgLoader.loadImage(getActivity(), mIvHeadimg, detailBean.getSponsorHeadimg(), R.drawable.head_img);
        //
        if (mTvNickname != null)
            mTvNickname.setText(StringUtils.isEmpty(detailBean.getSponsorNickname()) ? "" : detailBean.getSponsorNickname());
        //
        if (mTvContent != null)
            mTvContent.setText(StringUtils.isEmpty(detailBean.getTaskTitle()) ? "" : detailBean.getTaskTitle());
        if (mTvCreateTime != null)
            mTvCreateTime.setText(StringUtils.isEmpty(detailBean.getSponsorTime()) ? "" : detailBean.getSponsorTime());
        //
        if (mTvTimeArea != null)
            mTvTimeArea.setText(StringUtils.isEmpty(detailBean.getTaskTimeArea()) ? "参考详情" : detailBean.getTaskTimeArea());
        if (mTvSex != null)
            mTvSex.setText(StringUtils.isEmpty(detailBean.getSex()) ? "不限" : detailBean.getSex());
        //
        if (mTvWelfare != null)
            mTvWelfare.setText(StringUtils.isEmpty(detailBean.getReward()) ? "无" : detailBean.getReward());
        if (mTvWelfarePrice != null) mTvWelfarePrice.setText("￥" + detailBean.getRewardPrice());
        //
        if (mTvContact != null)
            mTvContact.setText(StringUtils.isEmpty(detailBean.getSponsorContact()) ? "无" : detailBean.getSponsorContact());
        if (mTvSelfDesc != null)
            mTvSelfDesc.setText(StringUtils.isEmpty(detailBean.getHelpContent()) ? "这个人很懒、没有任详细描述" : detailBean.getHelpContent());
        //
        if (mTvSupportNum != null)
            mTvSupportNum.setText(
                    (data.getEnrolledList() == null || data.getEnrolledList().size() == 0) ? "| 已报名人数 0 人"
                            : "| 已报名人数 " + data.getEnrolledList().size() + " 人");
        //显示状态
        showAct(data);
    }

    private Spanned getSupportNum(int num) {
        return Html.fromHtml("| 已报名人数 " + "<font style='color='red''>" + num + "</font> 人");
    }

    private void showAct(TaskDetailResult.TaskDetailDataBean data) {
        boolean isFoundStatus = false;
        TaskDetailResult.TaskDetailDataBean.TaskDetailBean detailBean = data.getTaskDetail();
        int status = detailBean.getTaskStatus();
        if (getActivity() == null) return;
        if (LoginStatusUtil.getLoginStatus(getActivity()) || !StringUtils.isEmpty(mUserName)) {
            if (mUserId == data.getTaskDetail().getTaskSponsorId()) {
                status = -1;                    //自己申请的任务, 不可申请
                isFoundStatus = true;
            }
        }

        if (!isFoundStatus && LoginStatusUtil.getLoginStatus(getActivity()) || !StringUtils.isEmpty(mUserName)) {
            List<TaskDetailResult.TaskDetailDataBean.EnrolledListBean> enrolledList = data.getEnrolledList();
            for (TaskDetailResult.TaskDetailDataBean.EnrolledListBean enrolledListBean : enrolledList) {
                if (mUserId != -1 && enrolledListBean.getTaskEnrolUserId() == mUserId) {
                    status = 5;                 //已报名，但未被发起方选中
                    isFoundStatus = true;
                }
            }
        }
        switch (status) {
            case -1:
                mTvAct.setEnabled(false);
                mTvAct.setText("不能申请自己发布的任务");
                mTvAct.setTextColor(getActivity().getResources().getColor(R.color.tvDisable));
                mTvAct.setBackgroundColor(getActivity().getResources().getColor(R.color.disable));
                break;
            case 1:

                mTvAct.setEnabled(true);
                mTvAct.setText("立即报名");
                mTvAct.setTextColor(getActivity().getResources().getColor(R.color.white));
                mTvAct.setBackgroundColor(getActivity().getResources().getColor(R.color.cyan));
                mTvAct.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        ToastUtils.showShort(App.getAppContext(), "报名");
                        connEnroll();
                    }
                });

                break;
            case 5:
                mTvAct.setEnabled(false);
                mTvAct.setText("已申请该任务，请耐心等待结果");
                mTvAct.setTextColor(getActivity().getResources().getColor(R.color.tvDisable));
                mTvAct.setBackgroundColor(getActivity().getResources().getColor(R.color.disable));
                break;
            default:
                mTvAct.setEnabled(false);
                mTvAct.setText("任务不可报名");
                mTvAct.setTextColor(getActivity().getResources().getColor(R.color.tvDisable));
                mTvAct.setBackgroundColor(getActivity().getResources().getColor(R.color.disable));
                break;
        }
    }

    private void connEnroll() {
        mPresenter.connEnroll();
    }

    @Override
    public void showRefreshingLoading(boolean isShow) {
        if (mRefreshing != null) mRefreshing.setRefreshing(isShow);
    }

    @Override
    public void finishCurrentActivity() {
        if (getActivity() != null)
            getActivity().finish();
    }

    @Override
    public void showSnackBar(String title, int showLength) {
        ToastUtils.showSnackbar(getCurrentFragmentRootView(), title, showLength);
    }

    @Override
    public void showLoading(boolean isShow) {
        if (isShow) showLoading("正在加载...");
        else hideLoading();
    }

}
